import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { PopService } from '../../../service/pop/pop.service';
import { BaseController } from '@shared/base-controller';
import { Constant, ServiceResult } from '@core/constant';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/index';
import { CartService } from '../../../service/cart/cart.service';
import { NzMessageService } from 'ng-zorro-antd';
import { CommService } from '../../../service/comm/comm.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'pop-product',
  templateUrl: './product.component.html',
  styleUrls: ['../../order/products/products.component.less'],
})
export class PopProductComponent extends BaseController implements OnInit {
  // 搜索表单
  q: any = {
    pageSize: 10,
    pageNumber: 0,
    sku: null,
    sap: null,
    brand: null,
  };
  total = 0;
  brands = [];
  list: { [proname: string]: any }[] = [];
  visible = false;
  imgSuffix = '';

  defaultUrl = './assets/tmp/img/dummy.png';

  constructor(
    public http: _HttpClient,
    private modal: ModalHelper,
    private popService: PopService,
    public injector: Injector,
    private cnt: Constant,
    private cartService: CartService,
    public msg: NzMessageService,
    private comm: CommService,
    private trans: TranslateService,
  ) {
    super(injector);
  }

  addBtn = false;
  cartBtn = false;

  ngOnInit() {
    this.addBtn = this.getAuths(this.cnt.authKey.cart.ADD_BTN);
    this.cartBtn = this.getAuths(this.cnt.authKey.cart.CART_BTN);
    this.imgSuffix = this.comm.getGoodsUrl();
    this.loadBrands();
    this.onScroll(false);
  }
  _onReuseInit() {
    this.onScroll(false);
  }

  previewImage = '';
  previewVisible = false;

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  minCount(prod) {
    if (prod.cart === undefined) {
      prod.cart = 0;
    }
    prod.cart--;
    if (prod.cart < 0) {
      prod.cart = 0;
      return;
    }
    this.doCart(prod);
  }

  addCount(prod) {
    if (prod.cart === undefined) {
      prod.cart = 0;
    }
    prod.cart++;
    this.doCart(prod);
  }

  doCart(prod) {
    this.popService
      .modifyCart(prod.id, prod.brand, prod.cart)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        if (data.status !== 200 && data.code !== 200) {
          this.msg.error(data.message);
        }
      });
  }

  modifyCart(prod, v) {
    this.popService
      .modifyCart(prod.id, prod.brand, v)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        if (data.status !== 200) {
          this.msg.error(data.message);
        }
      });
  }

  add() {
    // this.modal
    //   .createStatic(FormEditComponent, { i: { id: 0 } })
    //   .subscribe(() => this.st.reload());
  }

  popDto: any = {
    id: null,
    sku: null,
    sap: null,
    description: null,
    img: null,
    unit: null,
    qty: null,
    netWeight: null,
    grossWeight: null,
    exw: null,
    cif: null,
    priceUnit: null,
    status: null,
    brand: null,
    ctnQty: null,
    cm: null,
    details: [],
  };
  selectUrl = null;
  panels = [];
  view(pop) {
    this.popService
      .listPopById(pop.id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        // this.popDetail = data.data.rows;
        this.popDto = data.data;
        // 拼接图片地址
        // this.selectUrl = this.comm.getGoodsUrl() + this.selectProduct.img;
        this.selectUrl = this.comm.getGoodsUrl() + this.popDto.img;
        if (this.popDto.details.length > 0) {
          let flag = 0;
          for (const detail of this.popDto.details) {
            this.panels.push({
              detail: detail,
              active: flag === 0,
              disabled: false,
              name: 'POP Detail : ' + detail.sap,
              customStyle: {
                background: '#E9EBFE',
                'border-radius': '4px',
                'margin-bottom': '24px',
                border: '0px',
              },
            });
            flag++;
          }
        }
        this.visible = true;
      });
  }

  close(): void {
    this.panels = [];
    this.visible = false;
    this.previewVisible = false;
  }
  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }
  hasMore = true;
  loading = false;
  onScroll(append): void {
    if (this.loading) {
      return;
    }
    this.loading = true;
    if (append) {
      this.q.pageNumber = this.q.pageNumber + 1;
    } else {
      this.q.pageNumber = 1;
      this.hasMore = true;
    }
    if (this.hasMore) {
      const lang = this.trans.currentLang || this.trans.defaultLang;
      this.http
        .get(this.popService.productList2(), this.preHandle())
        .pipe(
          catchError(err => {
            this.loading = false;
            this.msg.create(
              'error',
              lang === 'en'
                ? 'Fail Loading,Please try again'
                : '加载数据失败，请重新加载',
            );
            return of(err);
          }),
        )
        .subscribe((res: any) => {
          if (
            res.data.rows.length === 0 ||
            res.data.rows.length < this.q.pageSize
          ) {
            this.hasMore = false;
          } else {
            this.hasMore = true;
          }
          if (append) {
            this.list = this.list.concat(res.data.rows);
          } else {
            this.list = res.data.rows;
          }
          this.loading = false;
        });
    } else {
      this.loading = false;
    }
  }
  preHandle() {
    return {
      sku: this.q.sku !== '' ? this.q.sku : null,
      sap: this.q.sap !== '' ? this.q.sap : null,
      brand: this.q.brand !== '' ? this.q.brand : null,
      pageSize: this.q.pageSize,
      pageNumber: this.q.pageNumber,
    };
  }
}
